//
//  CXBFileSizeValueTransformer.m
//  CocoaXBI
//


#import "CXBFileSizeValueTransformer.h"


@implementation CXBFileSizeValueTransformer
+ (Class)transformedValueClass {
    return [NSString class];
}

+ (BOOL)allowsReverseTransformation {
    return NO;
}

- (id)transformedValue:(id)value {
    
    double fileSize;
    
    if (value == nil) return nil;
    
    if ([value respondsToSelector: @selector(doubleValue)]) {
        // handles NSNumber and NSString
        fileSize = [value doubleValue];
    } else {
        [NSException raise: NSInternalInconsistencyException format: @"Value (%@) does not respond to -doubleValue.", [value class]];
    }
    
    if (fileSize > 1<<30) {
        return [NSString stringWithFormat:@"%1.2f GB", fileSize/(double)(1<<30)];
    } else if (fileSize > 1<<20) {
        return [NSString stringWithFormat:@"%1.2f MB", fileSize/(double)(1<<20)];
    } else if (fileSize > 1<<10) {
        return [NSString stringWithFormat:@"%1.2f KB", fileSize/(double)(1<<10)];
    } else {
        return [NSString stringWithFormat:@"%i bytes", (int)fileSize];
    }
}
@end
